/**
 * 
 */
package br.embedded.socialapp.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import br.edu.ufcg.embedded.util.FileManager;


/**
 * @author daniel
 *
 */
public class FriendshipDAO
{	
	private static FriendshipDAO singleton;
	
	private FriendshipDAO()
	{
		ConfigurationReader.readAllParameters();
	}
	
	public static FriendshipDAO getInstance()
	{
		if (singleton == null)
			singleton = new FriendshipDAO();
		return singleton;
	}
	
	public synchronized void truncate()
	{
		Connection connection = null;
		Statement statement = null;
		
		try {
			Class.forName(ConfigurationReader.DRIVER);
			connection = DriverManager.getConnection(ConfigurationReader.CONNECTION, ConfigurationReader.USER, ConfigurationReader.PWD);
			statement = connection.createStatement();
			
			statement.execute("truncate table calculated_friendship;");
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally
		{
			if (statement != null)
			{
				try {
					statement.close();
				}
				catch (SQLException sqlex)
				{}
			}
			if (connection != null)
			{
				try{
					connection.close();
				}
				catch(SQLException sqlex)
				{}
			}
		}
	}
	
	public synchronized void bulkInsert(List<String> files)
	{
		for (String file : files) {

			Connection connection = null;
			Statement statement = null;

			try {
				Class.forName(ConfigurationReader.DRIVER);
				connection = DriverManager.getConnection(ConfigurationReader.CONNECTION, ConfigurationReader.USER, ConfigurationReader.PWD);
				statement = connection.createStatement();

				statement.execute("COPY calculated_friendship FROM '" + file + "' WITH DELIMITER ';'");

			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			finally
			{
				if (statement != null)
				{
					try {
						statement.close();
					}
					catch (SQLException sqlex)
					{}
				}
				if (connection != null)
				{
					try{
						connection.close();
					}
					catch(SQLException sqlex)
					{}
				}

				FileManager.delete(file);
			}
		}
	}
}
